package org.vnl.platform.web.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import org.apache.commons.lang3.StringUtils;

/**
 * 控制了輸入及輸出的編碼,預設為UTF-8,可以利用 init-param來設定,其可用參數名為ENCODING.
 * @author Vaughan
 *
 */
public class EncodingFilter implements Filter {

    private static String _ENCODING = "ENCODING";
    private static String _DEFAULT_ENCODING = "UTF-8";
    
    private String encoding;
    
    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest arg0, ServletResponse arg1, FilterChain arg2) throws IOException, ServletException {
        arg0.setCharacterEncoding(encoding);
        arg1.setCharacterEncoding(encoding);
        arg2.doFilter(arg0, arg1);
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {
        encoding = arg0.getInitParameter(_ENCODING);
        if (StringUtils.isBlank(encoding)) {
            encoding = _DEFAULT_ENCODING;
        }
    }

}
